import org.apache.poi.common.usermodel.HyperlinkType;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;

public class ExcelTest {
    public static void main(String[] args) throws IOException {
        //TODO 创建excel文件和工作簿
        String filePath = "D:/example.xlsx";
        String sheetName = "Link2s";
        File file = new File(filePath);
        Workbook workbook = null;
        if (!file.exists()) {
            workbook = new XSSFWorkbook();
            workbook.createSheet(sheetName);
            saveExcel(workbook,filePath);
            System.out.println("文件不存在，已创建；并创建Sheet【"+ sheetName +"】");
        }

        //TODO 新建工作簿（若工作簿名称重复则会选择已创建）
        Sheet sheet = null;
        try (FileInputStream fis = new FileInputStream(file)) {
            workbook = new XSSFWorkbook(fis);
            sheet = workbook.getSheet(sheetName);
            if (sheet == null) {
                sheet = workbook.createSheet(sheetName);
                System.err.println("Sheet【"+ sheetName +"】不存在，已创建");
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        //TODO 开始工作

        // 创建超链接
        CreationHelper creationHelper = workbook.getCreationHelper();
        Hyperlink hyperlink = creationHelper.createHyperlink(HyperlinkType.URL);
        String paths = "..//引绰济辽//部门工作//图纸台账-程悦航//施工蓝图2023.4.29//1文得根水利枢纽//3枢纽二标//1主坝//826-JB6-1-7~14混凝土防渗墙契型墙体施工图//826-JB6-1-10 混凝土防渗墙楔形体施工图.pdf";
        Path p = Paths.get(paths);
        hyperlink.setAddress(p.toString());

        // 创建单元格并添加超链接
        Row row = sheet.createRow(0);
        Cell cell = row.createCell(0);
        cell.setCellValue("点击这里");
        cell.setHyperlink(hyperlink);
        CellStyle cellStyle = cell.getCellStyle();
        Font font = workbook.getFontAt(cellStyle.getFontIndexAsInt());
        font.setColor(IndexedColors.BLUE.getIndex());
        cellStyle.setFont(font);
        cell.setCellStyle(cellStyle);

        saveExcel(workbook,filePath);

    }

    public static void saveExcel(Workbook workbook,String path){
        // 保存Excel文件
        try (FileOutputStream outputStream = new FileOutputStream(path)) {
            workbook.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
